<?php

/**
* 套装稿件
*/

define('IN_ECS', true);
define('DF_ACT_ID', 9999);
require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_goods.php');
$exc = new exchange($ecs->table("goods_aa"), $db, 'act_id', 'act_name');

/*------------------------------------------------------ */
//-- 添加活动
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add')
{
    /* 权限判断 */
    admin_priv('package_manage');

    /* 组合商品 */
    $group_goods_list = array();
    $sql = "DELETE FROM " .$ecs->table('package_goods') .
            " WHERE package_id = 0 AND admin_id = '$_SESSION[admin_id]'";

    $db->query($sql);

    /* 初始化信息 */
    $start_time = local_date('Y-m-d H:i');
    $end_time   = local_date('Y-m-d H:i', strtotime('+1 month'));
    $package     = array('package_price'=>'', 'start_time' => $start_time, 'end_time' => $end_time);

    $smarty->assign('package',      $package);
    $smarty->assign('ur_here',      $_LANG['14_goods_aa_add']);
    $smarty->assign('action_link',  array('text' => $_LANG['14_goods_aa_list'], 'href'=>'goods_aa.php?act=list'));
    $smarty->assign('cat_list',     cat_list());
    $smarty->assign('form_action',  'insert');
	$smarty->assign('activity_list_options', get_goods_bbs(2 , 0, false));//活动类型
	$smarty->assign('cat_list2_options',	 cat_list2(0,0, true));//稿件分类
	

    assign_query_info();
    $smarty->display('goods_aa_info.htm');
}

elseif ($_REQUEST['act'] =='insert')
{
    /* 权限判断 */
    admin_priv('package_manage');

    $sql = "SELECT COUNT(*) ".
           " FROM " . $ecs->table('goods_aa').
           " WHERE act_name='" . $_POST['act_name'] . "'" ;
    if ($db->getOne($sql))
    {
        sys_msg(sprintf($_LANG['package_exist'],  $_POST['act_name']) , 1);
    }

    /* 插入数据 */
	$record = array('act_name' => $_POST['act_name'],'act_type'=>$_POST['act_type'], 'act_desc' => $_POST['desc'],'act_time'=>gmtime(),'cat2_id'=>$_POST['cat2_id']);
    $db->AutoExecute($ecs->table('goods_aa'),$record,'INSERT');

    /* 返回ID */
    $package_id = $db->insert_id();
	if($package_id>0){
		$sql = "UPDATE " . $GLOBALS['ecs']->table('goods_aa_data') . " SET " . " package_id = '$package_id'  WHERE package_id='0' AND admin_id = '$_SESSION[admin_id]'";
		$GLOBALS['db']->query($sql);
	}

    admin_log($_POST['act_name'],'add','goods_aa');
    $link[] = array('text' => $_LANG['back_list'], 'href'=>'goods_aa.php?act=list');
    $link[] = array('text' => $_LANG['continue_add'], 'href'=>'goods_aa.php?act=add');
    sys_msg($_LANG['add_succeed'],0,$link);
}

/*------------------------------------------------------ */
//-- 编辑活动
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit')
{
    /* 权限判断 */
    //admin_priv('package_manage');

    $package            = get_goods_aa_info($_REQUEST['id']);
    $package_goods_list = get_goods_aa_goods($_REQUEST['id']); // 礼包商品

    $smarty->assign('package',           $package);
    $smarty->assign('ur_here',           $_LANG['package_edit']);
    $smarty->assign('action_link',       array('text' => $_LANG['14_goods_aa_list'], 'href'=>'goods_aa.php?act=list&' . list_link_postfix()));
    $smarty->assign('cat_list',     cat_list());
    $smarty->assign('brand_list',   get_brand_list());
    $smarty->assign('form_action',       'update');
    $smarty->assign('package_goods_list', $package_goods_list);
	$smarty->assign('activity_list_options', get_goods_bbs(2 , $package['act_type'], false));//活动类型
	$smarty->assign('cat_list2_options',	 cat_list2(0,$package['cat2_id'], true));//稿件分类

    assign_query_info();
    $smarty->display('goods_aa_info.htm');

}
elseif ($_REQUEST['act'] =='update')
{
    /* 权限判断 */
    //admin_priv('package_manage');

    /* 检查活动重名 */
    $sql = "SELECT COUNT(*) ".
           " FROM " . $ecs->table('goods_aa').
           " WHERE act_name='" . $_POST['act_name'] . "' AND act_id <> '" .  $_POST['id'] . "'" ;
    if ($db->getOne($sql))
    {
        sys_msg(sprintf($_LANG['package_exist'],  $_POST['act_name']) , 1);
    }

    /* 更新数据 */
    $record = array('act_name' => $_POST['act_name'],'act_type'=>$_POST['act_type'], 'act_desc' => $_POST['desc'],'cat2_id'=>$_POST['cat2_id']);
    $db->autoExecute($ecs->table('goods_aa'), $record, 'UPDATE', "act_id = '" . $_POST['id']."'" );

    admin_log($_POST['act_name'],'edit','goods_aa');
    $link[] = array('text' => $_LANG['back_list'], 'href'=>'goods_aa.php?act=list&' . list_link_postfix());
    sys_msg($_LANG['edit_succeed'],0,$link);
}

/*------------------------------------------------------ */
//-- 删除指定的活动
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('package_manage');

    $id = intval($_GET['id']);

    $rs = $exc->drop($id);
	if($rs){
		 $sql = "DELETE FROM " .$ecs->table('goods_aa_data') ." WHERE package_id='$id' ";
		 $db->query($sql);	
	}

    $url = 'goods_aa.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 活动列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'list')
{
    $smarty->assign('ur_here',      $_LANG['14_goods_aa_list']);
    $smarty->assign('action_link',  array('text' => $_LANG['14_goods_aa_add'], 'href'=>'goods_aa.php?act=add'));

    $packages = get_goods_aa_list();

    $smarty->assign('package_list', $packages['packages']);
    $smarty->assign('filter',       $packages['filter']);
    $smarty->assign('record_count', $packages['record_count']);
    $smarty->assign('page_count',   $packages['page_count']);

    $sort_flag  = sort_flag($packages['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    $smarty->assign('full_page',    1);
    assign_query_info();
    $smarty->display('goods_aa_list.htm');
}

/*------------------------------------------------------ */
//-- 查询、翻页、排序
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query')
{
    $packages = get_goods_aa_list();

    $smarty->assign('package_list', $packages['packages']);
    $smarty->assign('filter',       $packages['filter']);
    $smarty->assign('record_count', $packages['record_count']);
    $smarty->assign('page_count',   $packages['page_count']);

    $sort_flag  = sort_flag($packages['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('goods_aa_list.htm'), '',
        array('filter' => $packages['filter'], 'page_count' => $packages['page_count']));
}

/*------------------------------------------------------ */
//-- 编辑活动名称
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_act_name')
{
    check_authz_json('package_manage');

    $id = intval($_POST['id']);
    $val = json_str_iconv(trim($_POST['val']));

    /* 检查活动重名 */
    $sql = "SELECT COUNT(*) ".
           " FROM " . $ecs->table('goods_aa').
           " WHERE 1=1 "." AND act_name='$val' AND act_id <> '$id'" ;
    if ($db->getOne($sql))
    {
        make_json_error(sprintf($_LANG['package_exist'],  $val));
    }

    $exc->edit("act_name='$val'", $id);
    make_json_result(stripslashes($val));
}

/*------------------------------------------------------ */
//-- 搜索商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'search_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);
	$filters->type = 1; //稿件列表

    $arr = get_goods_list($filters);

    $opt = array();
    foreach ($arr AS $key => $val)
    {
        $opt[$key] = array('value' => $val['goods_id'],
                        'text' => $val['goods_name'],
                        'data' => $val['shop_price']);

        $opt[$key]['products'] = get_good_products($val['goods_id']);
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 搜索商品，仅返回名称及ID
/*------------------------------------------------------ */

//elseif ($_REQUEST['act'] == 'get_goods_list')
//{
//    include_once(ROOT_PATH . 'includes/cls_json.php');
//    $json = new JSON;
//
//    $filters = $json->decode($_GET['JSON']);
//
//    $arr = get_goods_list($filters);
//
//    $opt = array();
//    foreach ($arr AS $key => $val)
//    {
//        $opt[$key] = array('value' => $val['goods_id'],
//                        'text' => $val['goods_name'],
//                        'data' => $val['shop_price']);
//
//        $opt[$key]['products'] = get_good_products($val['goods_id']);
//    }
//
//    make_json_result($opt);
//}

/*------------------------------------------------------ */
//-- 增加一个稿件
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_package_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('package_manage');

    $fittings   = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $package_id = $arguments[0];
    $number     = $arguments[1];

    foreach ($fittings AS $val)
    {
        $val_array = explode('_', $val);
        if (!isset($val_array[1]) || $val_array[1] <= 0)
        {
            $val_array[1] = 0;
        }

		 $sql = "INSERT INTO " . $ecs->table('goods_aa_data') . " (package_id, goods_id, admin_id) " .
			"VALUES ('$package_id', '" . $val_array[0] . "', '$_SESSION[admin_id]')";
		$db->query($sql, 'SILENT');
    }

    $arr = get_goods_aa_goods($package_id);
    $opt = array();

    foreach ($arr AS $val)
    {
		$text = getTR($val);
        $opt[] = array('value'      =>$val['goods_id'],
                        'text'      => $text,
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 删除一个稿件
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'drop_package_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('package_manage');

    $fittings   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $package_id = $arguments[0];

	$goods_id = 0 ;
    foreach ($fittings AS $val)
    {
            $goods[] = $val;
    }
    if (!empty($goods))
    {
        $sql = "DELETE FROM " .$ecs->table('goods_aa_data') .
                " WHERE package_id='$package_id' AND " .db_create_in($goods, 'goods_id');
        if ($package_id == 0)
        {
            $sql .= " AND admin_id = '$_SESSION[admin_id]'";
        }
        $db->query($sql);
    }
 
    $arr = get_goods_aa_goods($package_id);
    $opt = array();

    foreach ($arr AS $val)
    {
		$text = getTR($val);
        $opt[] = array('value'      => $val['goods_id'],
                        'text'      => $text,
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($opt);
}


/**
 * 获取套装稿件列表
 *
 * @access  public
 *
 * @return void
 */
function get_goods_aa_list()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 查询条件 */
        $filter['keywords']   = empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keywords'] = json_str_iconv($filter['keywords']);
        }
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'act_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = (!empty($filter['keywords'])) ? " AND act_name like '%". mysql_like_quote($filter['keywords']) ."%'" : '';

        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('goods_aa') .
               " WHERE 1=1 " . $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 获活动数据 */
        $sql = "SELECT * ".
               " FROM " . $GLOBALS['ecs']->table('goods_aa') .
               " WHERE 1=1 " . $where .
               " ORDER by $filter[sort_by] $filter[sort_order] LIMIT ". $filter['start'] .", " . $filter['page_size'];

        $filter['keywords'] = stripslashes($filter['keywords']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $row = $GLOBALS['db']->getAll($sql);

    foreach ($row AS $key => $val)
    {
        $row[$key]['act_time'] = local_date($GLOBALS['_CFG']['time_format'], $val['act_time']);
    }

    $arr = array('packages' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

/**
*
* 获取套餐稿件信息
*/

function get_goods_aa_info($id){
   $id = is_numeric($id)?intval($id):0;
    $now = gmtime();
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('goods_aa') ." WHERE act_id='$id' ";

    $goods_aa = $GLOBALS['db']->getRow($sql);

	return $goods_aa;
}

/**
 * 保存某礼包的商品
 * @param   int     $package_id
 * @return  void
 */
function handle_packagep_goods($package_id)
{
    $sql = "UPDATE " . $GLOBALS['ecs']->table('package_goods') . " SET " .
            " package_id = '$package_id' " .
            " WHERE package_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    $GLOBALS['db']->query($sql);
}

function getTR( $goods){
	$act_list = 
	$rs  = '';
	if($goods){
		$rs .='<tr><td width="50"><input type="checkbox" name="box_select" value="'.$goods['goods_id'].'"/></td>';
		$rs .='<td width="120" height="120"><img src="../'.$goods['goods_img'].'" style="width:120px;height:120px;border:1px solid #ddd;"></td>';
		$rs .='<td>稿件名称：'.$goods['goods_name'].'<br/>'.'所属商品：'.$goods['cat_name'].'<br/>'.'适用行业：'.$goods['cat2_name'].'<br/>';
		$rs .='设计风格'.'：'.getSheJFG_one($goods['act_id']).'<br/>';
		$rs .='规格尺寸'.'：'.$goods['goods_size'].'<br/>';
		$rs .='</td>';
		$rs .='</tr>';
	}else{
		$rs = '<tr></tr>';
	}
	return $rs;
}

?>